/**
 * 
 */
package cn.springsoter.core.tool.config;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import cn.springsoter.core.tool.annotation.NotControllerResponseAdvice;
import cn.springsoter.core.tool.api.R;
import cn.springsoter.core.tool.api.ResultCode;
import cn.springsoter.core.tool.exception.ServiceException;

/**
 * 统一处理controller返回，如果不是返回的R对象，则自动封装成R对象
 * 
 * 如果想忽略封装，可以加注解 @NotControllerResponseAdvice
 * 
 * @author kevin
 *
 */
@ControllerAdvice(basePackages = {"cn.springsoter"})
public class ControllerResponseAdviceConfig implements ResponseBodyAdvice<Object> {

	@Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
		// response是R对象或者加了注解 @NotControllerResponseAdvice 都不进行拦截包装
        return !(methodParameter.getParameterType().isAssignableFrom(R.class)
                || methodParameter.hasMethodAnnotation(NotControllerResponseAdvice.class));
    }

    @Override
    public Object beforeBodyWrite(Object data, MethodParameter returnType, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest request, ServerHttpResponse response) {
        // String类型不能直接包装
        if (returnType.getGenericParameterType().equals(String.class)) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                // 将数据包装在R里后转换为json串进行返回
                return objectMapper.writeValueAsString(new R().data(data));
            } catch (JsonProcessingException e) {
                throw new ServiceException(ResultCode.INTERNAL_SERVER_ERROR);
            }
        }
        // 否则直接包装成ResultVo返回
        return new R().data(data);
    }


}
